package durst.data.json;

import java.sql.SQLException;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.mapper.helper.SimpleMapperHelper;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONObject;
import com.sdicons.json.model.JSONValue;

import durst.data.Account;
import durst.data.Friend;
import durst.data.dao.DaoFactory;

public class FriendJSONHelper implements SimpleMapperHelper {
	@Override
	public Class<Friend> getHelpedClass() {
		return Friend.class;
	}

	@Override
	public JSONValue toJSON(Object aPojo) throws MapperException {
		if (aPojo instanceof Friend && aPojo != null) {
			Friend friend = (Friend)aPojo;
			JSONObject ret = new JSONObject(); 

			if (friend.getTarget() == null || friend.getTarget().getFirstName() == null) {
				try {
					DaoFactory.getInstance().createDao(Account.class).refresh(friend.getTarget());
				} catch (SQLException e) {
					throw new MapperException("could not refresh Target object from DB!");
				}
			}
			
			ret.getValue().put("id", JSONMapper.toJSON(friend.getTarget().getId()));
			ret.getValue().put("name", JSONMapper.toJSON(friend.getTarget().getFullName()));
			ret.getValue().put("email", JSONMapper.toJSON(friend.getTarget().getEmail()));
			ret.getValue().put("username", JSONMapper.toJSON(friend.getTarget().getUsername()));
			return ret;
		}
		
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object toJava(JSONValue aValue, Class aRequestedClass) throws MapperException {
		// We won't be using this functionality
		return null;
	}
}
